import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'BaseView.dart';
import 'PhotoAlbumLogic.dart';
import 'PhotoGallery.dart';
import 'VideoPlayerScreen.dart';

/// 相册页面
class PhotoAlbumView extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return BaseView<PhotoAlbumLogic>(
      model: PhotoAlbumLogic(),               // 创建视图模型实例
      onModelReady: (model) => model.init(),  // 初始化模型
      builder: (context, logic, child) {
        return Scaffold(
          backgroundColor: Colors.white,      // 界面背景色
          appBar: _buildAppBar(context, logic),      // 自定义AppBar
          body: _buildBody(context, logic),   // 相册主体内容
        );
      },
    );
  }

  /// 自定义AppBar
  AppBar _buildAppBar(BuildContext context, PhotoAlbumLogic logic) {
    return AppBar(
      backgroundColor: Colors.purple,     // AppBar的背景颜色
      automaticallyImplyLeading: false,   // 不自动显示返回按钮
      title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,  // 主轴两端对齐
        children: [
          GestureDetector(
            // 设置返回操作
            onTap: () {
              Navigator.pop(context);
            },
            child: const Icon(Icons.arrow_back, size: 24, color: Colors.white),       // 返回按钮
          ),

          MediaSegmentedControl(logic: logic),
          
          const Icon(Icons.edit, size: 24, color: Colors.white),                      // 编辑按钮
        ],
      ),
      systemOverlayStyle: const SystemUiOverlayStyle(
        statusBarColor: Colors.purple,              // 状态栏颜色
        statusBarIconBrightness: Brightness.light,  // 设置状态栏图标为亮色系
        systemNavigationBarColor: Colors.purple,    // 设置底部导航栏颜色
      ),
    );
  }

  /// 构建相册的主体部分
  Widget _buildBody(BuildContext context, PhotoAlbumLogic logic) {
    if (logic.isLoading) {
      // 如果正在加载，则显示加载指示器
      return const Center(child: CircularProgressIndicator(color: Colors.purple));
    } else {
      // 加载完成，展示相册内容
      return Container(
        padding: const EdgeInsets.only(left: 15, right: 15, top: 15),
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        child: _buildPhotoList(context, logic),  // 构建相册列表
      );
    }
  }

  /// 构建相册列表，使用ListView分隔显示日期和照片
  Widget _buildPhotoList(BuildContext context, PhotoAlbumLogic logic) {
    return ListView.separated(
      itemCount: logic.dateFileList.length,
      separatorBuilder: (_, index) => const SizedBox(height: 20),  // 设置列表项之间的间隔
      itemBuilder: (context, index) {
        DateTime dateTime = logic.dateFileList[index].creationTime;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 显示照片的日期
            Text("${dateTime.year}-${dateTime.month}-${dateTime.day}",
                style: const TextStyle(fontSize: 15, color: Colors.red),
            ),
            const SizedBox(height: 20),
            // 构建每日的照片/视频缩略图显示
            _buildPhotoWrap(context, logic, index),
          ],
        );
      },
    );
  }

  /// 构建每日照片的Wrap布局，用于显示照片/视频缩略图
  Widget _buildPhotoWrap(BuildContext context, PhotoAlbumLogic logic, int index) {
    final dateFile = logic.dateFileList[index]; // 获取当前日期的媒体集合

    return Wrap(
      spacing: 15,      // 水平间距
      runSpacing: 15,   // 垂直间距
      children: List.generate(
        dateFile.dateMediaInfoList.length,
            (wrapIndex) {
          final mediaInfo = dateFile.dateMediaInfoList[wrapIndex];
          return GestureDetector(
            onTap: () {
              if (mediaInfo.isVideo) {
                // 如果是视频文件，调用视频播放器
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => VideoPlayerScreen(videoUrl: mediaInfo.path)
                    )
                );
              } else {
                // 如果是图片文件，收集所有图片路径，调用图片画廊
                List<String> imagePaths = dateFile.dateMediaInfoList
                    .where((item) => !item.isVideo)
                    .map((item) => item.path)
                    .toList();
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => PhotoGallery(imageUrls: imagePaths)
                    )
                );
              }
            },
            child: Container(
              height: 75,  // 设置容器高度
              width: (MediaQuery.of(context).size.width - 15 * 4) / 3,  // 计算容器宽度
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(3),                 // 设置圆角边框
                image: DecorationImage(
                  image: MemoryImage(mediaInfo.thumbnailData),
                  fit: BoxFit.cover,  // 图片填充方式
                ),
              ),
              child: mediaInfo.isVideo
              // 视频文件显示播放图标
                  ? const UnconstrainedBox( child: Icon(Icons.play_arrow, size: 24, color: Colors.white),)
              // 非视频文件不显示图标
                  : Container(),
            ),
          );
        },
      ),
    );
  }

}



class MediaSegmentedControl extends StatefulWidget {
  final PhotoAlbumLogic logic;

  MediaSegmentedControl({Key? key, required this.logic}) : super(key: key);

  @override
  _MediaSegmentedControlState createState() => _MediaSegmentedControlState();
}

class _MediaSegmentedControlState extends State<MediaSegmentedControl> {
  int _selectedSegment = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        CupertinoSegmentedControl<int>(
          children: const {
            0: Padding(
              padding: EdgeInsets.symmetric(vertical: 5, horizontal: 8),
              child: Text('所有', style: TextStyle(fontSize: 15)),
            ),
            1: Padding(
              padding: EdgeInsets.symmetric(vertical: 5, horizontal: 8),
              child: Text('图片', style: TextStyle(fontSize: 15)),
            ),
            2: Padding(
              padding: EdgeInsets.symmetric(vertical: 5, horizontal: 8),
              child: Text('视频', style: TextStyle(fontSize: 15)),
            ),
          },
          onValueChanged: (int value) {
            // 更新数据源
            if (value == 0) {
              widget.logic.currentMediaType = MediaType.all;
            }else if (value == 1) {
              widget.logic.currentMediaType = MediaType.image;
            }else if (value == 2) {
              widget.logic.currentMediaType = MediaType.video;
            }
            // 更新UI
            setState(() {
              _selectedSegment = value;
            });
          },
          groupValue: _selectedSegment,
        ),
      ],
    );
  }
}
